<template>
    <view class="countdown-container">
        <!-- <nut-countdown :start-time="start" :end-time="end" 
        @time-change="formatTimes"
        @on-finish="handleCountdownFinish">
            <div class="countdown-content">
                倒计时：
                <span class="time">{{ timeData.hours }}</span>:
                <span class="time">{{ timeData.minutes }}</span>:
                <span class="time">{{ timeData.seconds }}</span>
            </div>
        </nut-countdown> -->
        <text>倒计时：</text>
        <nut-countdown ref="myCountdown" @paused="handlePause" :start-time="start" :end-time="end" format="HH:mm:ss"
            @on-end="handleCountdownFinish" />
    </view>
    <!-- <view class="countdown-placeholder"></view> -->
    <view class="answer-page" :class="fontClass">
        <QuestionHeader :current-question="currentQuestion" :question-data="questionData"
            :show-setting-modal="showSettingModal" :show-feedback="showFeedback" :autoNextEnabled="autoNextEnabled"
            :request-handler="handleRequest" @update:showSettingModal="showSettingModal = $event"
            @update:showFeedback="showFeedback = $event" @set-font-size="setFontClass"
            @update:autoNextEnabled="onAutoNextChange" />

        <QuestionContent :question-data="questionData" :selected-option="selectedOption" :is-correct="isCorrect"
            :show-analysis-content="showAnalysisContent" :answer-text="answerText"
            @update:selectedOption="selectedOption = $event" @onClick:Option="onClickOption" />
        <view class="auto-submit-tip">
            注意:退出考试页面将自动提交试卷
        </view>
        <!-- 确认按钮 -->
        <!-- <view class="confirm-btn"> -->
        <!-- <nut-button type="info" block @click="confirmAnswer">确认</nut-button> -->
        <!-- </view> -->
        <BottomNav :show-card-modal="showCardModal" :current-question="currentQuestion" :question-list="questionList"
            :AnalyseOrSubmit="AnalyseOrSubmit" :isCollected="isCollected" :answer-record-list="answerRecordList"
            :is-question-correct="isQuestionCorrect" :is-question-answered="isQuestionAnswered"
            @update:showCardModal="showCardModal = $event" @update:showAnalysis="showAnalysis"
            @prevQuestion="prevQuestion" @nextQuestion="nextQuestion" @goToQuestion="goToQuestion"
            @toggleCollect="toggleCollect" @submitExam="submitExam" />
    </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, reactive, onBeforeUnmount } from 'vue'
import QuestionHeader from '../../components/questionHeader.vue'
import QuestionContent from '../../components/questionContent.vue'
import BottomNav from '../../components/bottomNav.vue'
import Taro from '@tarojs/taro'
import config from '../../config'

//控制是否暂停
// const paused = ref(false);
// 当前时间戳
const now = new Date().getTime()
const createTime = new Date();
const start = ref(now) // 开始时间
const end = ref(now + 60 * 1000 * 90) // 结束时间：当前时间 + 60 秒
const myCountdown = ref(null);
// 时间数据响应式对象
const timeData = reactive({
    hours: '00',
    minutes: '00',
    seconds: '00'
})
const unikey = ref('');
//禁用标记，当选出正确答案，禁用选项(未启用)
const disableFlag = ref(false)
//问题集合列表
const questionList = ref([])
//当前问题索引
const currentQuestion = ref(0)
//选项集合
const selectedOption = ref([])
//判断答案是否正确标识(用于题目背景颜色)
const isCorrect = ref(null)
//判断答案是否正确标识的副本（避免改变选项的背景样式）
const transcript = ref(null)
//题目解析控制器
const showAnalysisContent = ref(false)
//设置弹窗是否显示
const showSettingModal = ref(false)
//反馈弹窗是否显示
const showFeedback = ref(false)
//答题卡(卡片)弹窗是否显示
const showCardModal = ref(false)
// 获取页面参数
const query = ref('')
const AnalyseOrSubmit = ref(false);
const autoNextEnabled = ref(false) // 默认不开启自动跳转
//当前问题对象
const questionData = ref({
    id: null,
    type: 1, // 题型：1-单选 2-多选 3-判断
    title: '',
    options: [], // 解析后的选项
    correctAnswer: '',
    analysis: ''
})
//用户答题记录需返回到后端的样式
const record = ref({
    userId: null,
    questionId: null,
    userAnswer: '',
    correct: null,
    updateTime: ''
})
//用于答题记录集合
const answerRecordList = ref([])
//用于错题记录集合(未使用)
const wrongRecordList = ref([])
//保存对应题号。用于按照题号找下标。按照下标找分数（未使用）
const idFlag = ref(new Array(200).fill(0))
//用于保存对应题目的分值(数组的值为，对应分数)（未使用）
const score = ref(new Array(200).fill(0))
//保存考试的时间
const examTime = ref(0);
//收藏对象
const collectData = ref({
    userId: null,
    questionId: null,
    createTime: '',
    delFlag: null
});
//收藏集合（）
const collectList = ref([]);
//已答题集合(未启用)
// const answeredQuestions = ref(Array(questionList.value.length).fill(false))
// 是否收藏
const isCollected = ref(false)
// 当前题目数据
// const currentQuestionData = computed(() => questionList.value[currentQuestion.value] || {})

// 格式化剩余时间
const formatTimes = (totalMilliseconds) => {
    console.log('剩余时间:', totalMilliseconds)
    const totalSeconds = Math.floor(totalMilliseconds / 1000)
    const hours = String(Math.floor(totalSeconds / 3600)).padStart(2, '0')
    const minutes = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0')
    const seconds = String(totalSeconds % 60).padStart(2, '0')
    timeData.hours = hours
    timeData.minutes = minutes
    timeData.seconds = seconds
}
//用于传递考试详情的信息（分数、考试事件）
const exam = ref({});
// 倒计时结束回调
const handleCountdownFinish = () => {
    console.log('考试时间到！')
}
const handlePause = (v) => {
    // 剩餘的时间（毫秒）
    const elapsed = v
    // 总倒计时时间（毫秒）
    const totalDuration = end.value - start.value
    const remainingTime = Math.max(0, totalDuration - elapsed)
    // 格式化剩余时间为 HH:mm:ss
    const formattedTime = formatRemainingTime(remainingTime)
    examTime.value = formattedTime
}
// 将毫秒转换为 HH:mm:ss 格式
const formatRemainingTime = (milliseconds) => {
    let totalSeconds = Math.floor(milliseconds / 1000)
    const hours = String(Math.floor(totalSeconds / 3600)).padStart(2, '0')
    const minutes = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0')
    const seconds = String(totalSeconds % 60).padStart(2, '0')

    return `${hours}:${minutes}:${seconds}`
}
const userId = ref(null);
//点击提交按钮的方法
function submitExam() {
    setDataToPage();
}
//携带数据跳转页面
function setDataToPage() {
    //暂停倒计时
    myCountdown.value.pause();
    //将数据保存到考试记录中
    saveExamRecord();


}
function caculateScore() {
    let score = 0;
    answerRecordList.value.forEach(item => {
        if (item.correct === 1) {
            score += item.score;
        }
    });
    return score;
}
async function saveExamRecord() {
    //传给后端的格式
    // const userId = Taro.getStorageSync('id') // 示例：从本地缓存获取用户ID
    //错欸id列表，包含错题和未做的题
    const wrongQuestionIds = [
        ...answerRecordList.value
            .filter(record => record.correct !== 1)
            .map(record => record.questionId),
        ...questionList.value
            .filter(r => !answerRecordList.value.some(ans => ans.questionId === r.id))
            .map(r => r.id)
    ];
    // 初始化分类容器
    const categorizedQuestionIds = {
        singleChoice: [],  // 单选题 type === 1
        multipleChoice: [], // 多选题 type === 2
        trueFalse: []       // 判断题 type === 3
    };
    let singleWrongNum = 0;
    let multipleWrongNum = 0;
    let judgeWrongNum = 0;
    // 遍历 questionList 并分类
    questionList.value.forEach(question => {
        const isWrong = wrongQuestionIds.includes(question.id);
        switch (question.type) {
            case 1:
                categorizedQuestionIds.singleChoice.push(question.id);
                if (isWrong) {
                    singleWrongNum++;
                }
                break;
            case 2:
                categorizedQuestionIds.multipleChoice.push(question.id);
                if (isWrong) {
                    multipleWrongNum++;
                }
                break;
            case 3:
                categorizedQuestionIds.trueFalse.push(question.id);
                if (isWrong) {
                    judgeWrongNum++;
                }
                break;
            default:
                console.warn('未知题型:', question.type);
                break;
        }
    });
    const filteredRecords = answerRecordList.value.map(record => ({
        questionId: record.questionId,
        userAnswer: record.userAnswer
    }));
    const answerInfo = {
        examTime: examTime.value,
        singleWrongNum: singleWrongNum,
        multiWrongNum: multipleWrongNum,
        judgeWrongNum: judgeWrongNum,
        idAndAnswer: filteredRecords
    }
    let complete = questionList.value.length === answerRecordList.value.length ? 1 : 0;
    let passed = caculateScore() >= 60 ? 1 : 0;
    const examRecord = {
        userId: userId.value,
        type: 0,//0 模拟测试，1 真题测试
        questions: JSON.stringify(categorizedQuestionIds),
        answerInfo: JSON.stringify(answerInfo),
        wrongQuestions: JSON.stringify(wrongQuestionIds),
        score: caculateScore(),
        complete: complete,
        passed: passed,
        createTime: formatTime(createTime),
        delFlag: 0
    };
    console.log("flajdfadfaf", examRecord);
    try {
        const wxRequest = config.wxPromisify(wx.request)
        const res = await wxRequest({
            url: `${config.apiUrl}/exam/saveOne`,
            method: 'POST',
            header: { 'content-type': 'application/json' },
            data: examRecord
        })
        if (res.data.code === '0') {
            unikey.value = res.data.data;
            handleExit();
        }
    } catch (err) {
        console.error('保存考试记录失败', err)
    }

}
//页面加载时获取题目列表(随机刷题不需要页面携带数据)
onMounted(() => {
    userId.value = Taro.getStorageSync('id');
    if (userId.value == null) {
        return Taro.navigateTo({
            url: '/pages/profile/index'
        })
    }
    //确保组件加载完毕
    if (myCountdown.value) {
        fetchQuestions()
    }
})


// 获取题目数据
const fetchQuestions = async () => {
    try {
        const wxRequest = config.wxPromisify(wx.request)
        const res = await wxRequest({
            url: `${config.apiUrl}/question/findMockTest`,
            method: 'GET',
            header: { 'content-type': 'application/json' }
        })
        //获取收藏列表
        const resCllotion = await wxRequest({
            url: `${config.apiUrl}/collection/find/${userId.value}`,
            method: 'GET',
            header: { 'content-type': 'application/json' }
        })

        console.log('接口返回:', res.data)

        if (res.data.code === '0') {
            questionList.value = res.data.data || []
            collectList.value = resCllotion.data.data || []
            updateQuestionData()
            isQuestionCollected(questionData.value.id)
            //(会导致保存时存在.数组初始化,但内容都是空值)
            // answerRecordList.value = Array(questionList.value.length).fill().map(() => (record));
        } else {
            Taro.showToast({ title: '获取题目失败', icon: 'none' })
        }

    } catch (err) {
        console.error('请求失败:', err)
        Taro.showToast({ title: '网络错误', icon: 'none' })
    }
}
//表格的点击事件
const onClickOption = (val) => {
    console.log('点击了选项:', val)
    isCorrect.value = '0'
    transcript.value = '0'
    if (questionData.value.type === 2) {
        // 多选题：确保是数组
        const arr = selectedOption.value || []

        const index = arr.indexOf(val)
        if (index > -1) {
            // 已存在则移除
            selectedOption.value = arr.filter(item => item !== val)
        } else {
            // 不存在则添加
            selectedOption.value = [...arr, val]
        }
    } else {
        // 单选/判断题
        selectedOption.value = val
    }
}
// 判断是否正确(模拟考试中不改变背景颜色)
const isQuestionCorrect = (index) => {
    const questionId = questionList.value[index]?.id;
    const existingIndex = answerRecordList.value.findIndex(r => r.questionId === questionId);
    if (existingIndex === -1) {
        return 2;
    }
    const q = answerRecordList.value[existingIndex]?.correct
    console.log("记录对象判断答题卡是否正确：", q)
    return 3;

    // const correct = formatCorrectAnswer(q.correctAnswer)
    // const user = formatCorrectAnswer(q.userAnswer)
}
// 判断是否已答题(答题卡弹窗)
const isQuestionAnswered = (index) => {
    const questionId = questionList.value[index]?.id;
    const existingIndex = answerRecordList.value.findIndex(r => r.questionId === questionId);
    if (existingIndex === -1) {
        return false;
    }
    // const q = answerRecordList.value[existingIndex]?.userAnswer
    // if (!q) {
    //     return false;
    // }
    const q = answerRecordList.value[existingIndex]?.correct
    // console.log("q的值为",q);
    // console.log("记录对象判断user：", q !== 2)
    return q !== 2
}
//判断是否收藏
function isQuestionCollected(questionId) {
    console.log('判断是否收藏id', questionId);
    const existingIndex = collectList.value.findIndex(item => item.questionId === questionId);
    if (existingIndex > -1) {

    }
    isCollected.value = (existingIndex > -1);
    console.log('判断是否收藏', isCollected.value);
}
// 回答答案文字
const answerText = computed(() => {
    const ans = questionData.value.correctAnswer
    if (typeof ans === 'string') return ans
    if (Array.isArray(ans)) return ans.join(', ')
    return ''
})
// 格式化时间为 "YYYY-MM-DD HH:mm"
const formatTime = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从 0 开始
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}`
}
// 将正确答案统一转为字符串格式（如 ["A","B"] → "AB"）
const formatCorrectAnswer = (answer) => {
    if (!answer) return ''
    if (Array.isArray(answer)) {
        // 如果是数组，去重后排序并拼接成字符串
        return [...new Set(answer)].sort().join('')
    } else if (typeof answer === 'string') {
        // 如果是字符串，去除非字母字符后排序
        return answer.replace(/[^A-Z]/g, '').split('').sort().join('')
    }
    return ''
}
// 更新当前题目数据
const updateQuestionData = () => {
    if (questionList.value.length === 0) return

    const current = questionList.value[currentQuestion.value]

    // 查找答题记录
    const record = answerRecordList.value.find(r => r.questionId === current.id)
    //将当前问题的id存入数组中

    questionData.value = {
        id: current.id,
        type: current.type,
        title: current.questionText,
        options: JSON.parse(current.answerOptions),
        correctAnswer: formatCorrectAnswer(current.correctAnswer),
        analysis: current.answerAnalysis,
        userAnswer: record ? record.userAnswer : null
    }

    // 根据题型初始化 selectedOption
    if (current.type === 2) {
        // 多选题
        selectedOption.value = record && record.userAnswer ? [...record.userAnswer] : []
    } else {
        // 单选/判断题
        selectedOption.value = record ? record.userAnswer : ''
    }

    // 设置是否正确状态
    if (record) {
        transcript.value = record.correct === 1 ? '1' : '-1'
    } else {
        transcript.value = '0'
    }
}
// 收藏切换
const toggleCollect = () => {
    isCollected.value = !isCollected.value
    let questionId = questionData.value.id;
    if (isCollected.value) {
        // 收藏
        collectData.value = {
            userId: 1,
            questionId: questionId,
            createTime: formatTime(new Date()),
            delFlag: 0
        }
        collectList.value.push(collectData.value)
    } else {
        // 取消收藏
        const index = collectList.value.findIndex(item => item.questionId === questionId)
        if (index > -1) {
            collectList.value[index].delFlag = 1
        }
    }
    console.log('收藏列表', collectList.value)
    Taro.showToast({
        title: isCollected.value ? '已收藏' : '已取消收藏',
        icon: 'none'
    })

}
// 自动跳转开关变化
const onAutoNextChange = (val) => {
    autoNextEnabled.value = val
}
// 格式化答案为字符串存储（数组 → 字符串）
const formatAnswerForSave = (answer) => {
    if (!answer) return ''
    if (Array.isArray(answer)) {
        return answer.join('')
    }
    return answer
}
//保存答题记录
const saveAnswerRecord = (status) => {
    const current = questionList.value[currentQuestion.value]
    // const userId = Taro.getStorageSync('userId') || 1 // 示例：从本地缓存获取用户ID
    const questionId = current.id
    const userAnswer = selectedOption.value
    //1为单选，2多选，3判断
    // console.log("current.type:",current.type);
    const scoreOne = (current.type === 1 ? 0.5 : 1)
    // console.log("scoreOne:",scoreOne);
    //如果用户没有点击，则不保存数据（未启用）
    // if(userAnswer){
    //     return;
    // }
    let correct = 2 // 默认为无答案
    console.log("提交答案", isCorrect.value)
    if (status === 'submit') {
        if (transcript.value === '1') {
            console.log('提交答案1');
            correct = 1
        } else if (transcript.value === '-1') {
            if (userAnswer) {
                console.log('提交答案-1');
                correct = 0
            }
        }
    }
    const record = {
        userId: userId.value,
        questionId,
        userAnswer: formatAnswerForSave(userAnswer),
        correct,
        updateTime: formatTime(new Date()),
        score: scoreOne,
    }
    console.log('record', record);
    // 更新或新增记录
    const existingIndex = answerRecordList.value.findIndex(r => r.questionId === questionId)
    // const wrongExitIndex = wrongRecordList.value.findIndex(r => r.questionId === questionId)
    if (existingIndex > -1) {
        // 已存在则更新
        answerRecordList.value.splice(existingIndex, 1, record)
    } else {
        // 否则添加
        answerRecordList.value.push(record)
    }
    // if (wrongExitIndex > -1) {
    //     // 已存在则更新
    //     wrongRecordList.value.splice(wrongExitIndex, 1)
    // }else {
    //     // 否则添加
    //     wrongRecordList.value.push(record)
    // }
}
// 答题方法
const confirmAnswer = () => {
    const correct = questionData.value.correctAnswer
    const userAnswer = selectedOption.value
    if (questionData.value.type === 2) {
        // 多选题：排序后转字符串比对
        const correctArray = correct.split(',').filter(Boolean)
        const userArray = selectedOption.value || []
        const correctSorted = correctArray.sort().join('')
        const userSorted = userArray.sort().join('')
        console.log('用户答案排序后:', userSorted);
        console.log('正确答案排序后:', correctSorted);
        //模拟考试的时候不需要改变样式和判断
        if (userSorted === correctSorted) {
            isCorrect.value = '0'
            transcript.value = '1'
            //     disableFlag.value = true
            //     Taro.showToast({ title: '回答正确!', icon: 'success' })
        } else {
            isCorrect.value = '0'
            transcript.value = '-1'
            //     Taro.showToast({ title: '回答错误!', icon: 'none' })
        }
    } else {
        // 单选或判断题
        if (userAnswer === correct) {
            isCorrect.value = '0'
            transcript.value = '1'
            // disableFlag.value = true
            // Taro.showToast({ title: '回答正确!', icon: 'success' })
        } else {
            isCorrect.value = '0'
            transcript.value = '-1'
            // Taro.showToast({ title: '回答错误!', icon: 'none' })
        }
    }

    // 提交后保存记录
    saveAnswerRecord('submit');
    // 如果启用自动跳转且不是最后一题
    if (autoNextEnabled.value && currentQuestion.value < questionList.value.length - 1) {
        setTimeout(() => {
            nextQuestion()
        }, 500)
    }
}
// 显示解析
const showAnalysis = () => {
    //用于答案的处理，使点击解析时，能出现答案
    answerText.value = formatCorrectAnswer(questionData.value.correctAnswer);
    showAnalysisContent.value = !showAnalysisContent.value
}
//将封装的请求发给子组件方法
const handleRequest = () => {
    return config.wxPromisify(wx.request);
}
const prevQuestion = () => {
    confirmAnswer();
    if (currentQuestion.value > 0) {
        currentQuestion.value--
        resetQuestionState()
    }
}
// 提交所有记录到后端
const submitAllRecords = async () => {
    const wxRequest = config.wxPromisify(wx.request)
    try {
        if (answerRecordList.value.length !== 0) {
            const res = await wxRequest({
                url: `${config.apiUrl}/userAnswer/addAll`,
                method: 'POST',
                header: { 'content-type': 'application/json' },
                data: answerRecordList.value
            })
        }
        if (collectList.value.length !== 0) {
            const resCllotion = await wxRequest({
                url: `${config.apiUrl}/collection/save`,
                method: 'POST',
                header: { 'content-type': 'application/json' },
                data: collectList.value
            })
        }
        // if (res.data.code === '0' && resCllotion.data.code === '0') {
        //     Taro.showToast({ title: res.data.msg, icon: 'success' })
        // } else {
        //     Taro.showToast({ title: res.data.msg, icon: 'none' })
        // }
    } catch (err) {
        console.error('提交失败:', err)
        Taro.showToast({ title: '网络错误', icon: 'none' })
    }
}
const nextQuestion = () => {
    confirmAnswer();
    if (currentQuestion.value < questionList.value.length - 1) {
        currentQuestion.value++
        resetQuestionState()
    } else {
        // 已是最后一题，弹窗确认是否提交
        Taro.showModal({
            title: '提示',
            content: '您已完成全部题目，是否提交？',
            success: async (res) => {
                if (res.confirm) {
                    handleExit();
                    // Taro.reLaunch({ url: '/pages/index/index' }) // 跳转到首页
                }
            }
        })
    }
}
onBeforeUnmount(() => {
    submitExam();
})
// onUnmounted(() => {
//     // 页面卸载前执行
//     // submitExam();
// })
// 处理用户退出页面逻辑
const handleExit = async () => {
    await submitAllRecords();
    Taro.redirectTo({
        url: `/pages/recordDetails/recordDetails?unikey=${unikey.value}`
    })
    // Taro.reLaunch({ url: '/pages/index/index' }) // 强制跳转首页
}

const goToQuestion = (index) => {
    confirmAnswer();
    currentQuestion.value = index
    resetQuestionState()
}

const resetQuestionState = () => {
    // showAnalysisContent.value = false
    isCorrect.value = null
    transcript.value = null
    selectedOption.value = []
    updateQuestionData();
    isQuestionCollected(questionData.value.id);
}
</script>

<style lang="scss">
@use "../../components/common.scss";
</style>